package model;

import model.Point;

public class EC2 {
	
	public static int a;
	public static int b;
	public static int p;
	
	

	 public static int quyu(int f){
    	 int z=f/p;
    	 int mo= f-(z*p);
    	 if(mo>=0)
    		 return mo;
    	 else
    		 return mo+p;
     }
	 
	 public static Point beidian(Point p) {
		 int Xq=Integer.parseInt(p.getX());
		 int Yq=Integer.parseInt(p.getY());
		 int x=0;
		 int y=0;
	 		int m = (3 * Xq * Xq + a) * qiuni(2 * Yq);
	 		int k = quyu(m);
	 		int Sx = k * k - 2 * Xq;
	 		x = quyu(Sx);
	 		int Sy = -Yq + k * (Xq - x);
	 		y = quyu(Sy);
	 		return new Point(""+x,""+y);
	 	}
	 
	 public static int qiuni(int z) {
	 		int s = 0;
	 		int u = 0;
	 		do {
	 			s = u * z % p;
	 			u++;
	 		} while (s != 1);
	 		return u - 1;
	 	}
	 
	 public Point getMultiply(int n,Point p){
		 int Xq=Integer.parseInt(p.getX());
		 int Yq=Integer.parseInt(p.getY());
 		if (n == 1)
 			return p;
			// 倍点计算
			else if (n == 2) {return beidian(p);}
			// 点乘计算
			else {
				int k1,k,x=0,y=0;
				// 将2Q作为点P（x1，y1）
				Point temp=beidian(p);
				int x1 = Integer.parseInt(temp.getX());
				int y1 = Integer.parseInt(temp.getY());
				// 将Q （x2，y2）作为点加的另一个点
				int x2 = Xq;
				int y2 = Yq;
				// 循环实现点乘运算，nQ分解成2Q+(n-2)Q,每次加上一个Q直至算完nQ;
				for (int i = 1; i <= n - 2; i++) {
					if ((x2 - x1) >= 0) {
						k1 = (y2 - y1) * qiuni(x2 - x1);
						k = quyu(k1);
						int Sx = k * k - x1 - x2;
						x = quyu(Sx);
						int Sy = -y1 + k * (x1 - x);
						y = quyu(Sy);
					}else {
						k1 = (y1 - y2) * qiuni(x1 - x2);
						k = quyu(k1);
						int Sx = k * k - x1 - x2;
						x = quyu(Sx);
						int Sy = -y1 + k * (x1 - x);
						y = quyu(Sy);
					}
					x1 = x;
					y1 = y;
				}
				return new Point(""+x,""+y);		
     }   	
  }

	public static void main(String[] args) {
		EC2 ec=new EC2();
		ec.a=1;
		ec.b=1;
		ec.p=23;
		Point pub=ec.getMultiply(13, new Point("1","1"));
		System.out.println(pub);
		
	}
	 
}
